import React, { useState } from "react";
import { MessageList } from "./MessageList";
import { ChatInput } from "./ChatInput";
import { Message } from "@/types/chat";

interface ChatInterfaceProps {
  initialMessages?: Message[];
  onSendMessage?: (message: string) => Promise<void>;
}

export function ChatInterface({
  initialMessages = [],
  onSendMessage,
}: ChatInterfaceProps) {
  const [messages, setMessages] = useState<Message[]>(initialMessages);
  const [loading, setLoading] = useState(false);

  const handleSendMessage = async (content: string) => {
    // 添加用户消息
    const userMessage: Message = {
      role: "user",
      content,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setLoading(true);

    try {
      if (onSendMessage) {
        await onSendMessage(content);
      } else {
        // 模拟API响应的延迟
        await new Promise((resolve) => setTimeout(resolve, 1000));
        
        // 模拟AI回复
        const aiMessage: Message = {
          role: "assistant",
          content: `这是对"${content}"的模拟回复。在实际应用中，这里将是AI的响应。`,
          timestamp: new Date(),
        };
        
        setMessages((prev) => [...prev, aiMessage]);
      }
    } catch (error) {
      console.error("发送消息时出错:", error);
      // 可以在这里添加错误处理逻辑
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex h-full flex-col">
      <div className="flex-1 overflow-hidden">
        <MessageList messages={messages} loading={loading} />
      </div>
      <div className="border-t p-4 dark:border-gray-700">
        <ChatInput onSubmit={handleSendMessage} isLoading={loading} />
      </div>
    </div>
  );
} 